<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/23 0023
 * Time: 9:07
 */

namespace app\data\controller;

use think\Cache;
use think\Db;

class Obtain extends Base
{
  
  	public function dddd(){
        $key = 'AllCurrencyList';
        $list = Db::name('currency')
            ->alias('a')
            ->join('currency b','a.pid=b.cu_id')
            ->where(['a.pid'=>['>',0],'a.type'=>1])
            ->field('a.cu_id,a.title,b.title as platform')
            ->select();
      	//$re = ['b1'=>0,'b2'=>0,'b3'=>0,'s1'=>0,'s2'=>0,'s3'=>0];
        //Db::name('height_remind')->where(['uid'=>['<',999999]])->update($re);
        if(!$list)return false;
        foreach ($list as $k=>$v){
            $price = 'api error';
            switch ($v['platform']){               
                case 'ZB';
                    $api = 'http://api.zb.cn/data/v1/kline?market='.$v['title'].'_usdt&size=2&type=1day';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data->data))$price = $data->data[0][4];
                	
                    break;
                case 'OKEx';                   
                    $api = 'https://www.okex.com/api/spot/v3/instruments/'.strtoupper($v['title']).'-USDT/candles?granularity=86400';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data))$price = $data[1][4];;
                    break;
                case 'Huobi';
                    $api = "https://api.huobi.pro/market/history/kline?period=1day&size=2&symbol=".$v['title']."usdt";
                    $data = json_decode($this->cUrl($api));
                    if(isset($data->data[1]->close))$price =$data->data[1]->close;
                    break;
                case 'Binance';
                    $api = 'https://api.binance.com/api/v1/klines?symbol='.strtoupper($v['title']).'USDT&interval=1d&limit=2';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data[0]))$price =$data[0][4];	
                    break;
                case 'Gate.io';
                    $api = 'https://data.gateio.co/api2/1/candlestick2/'.$v['title'].'_usdt?group_sec=86400&range_hour=24';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data->data[0][2]))$price =$data->data[0][2];
                    break;
                default;
                    $price = 'api error';
                    break;
            }
            if($price != 'api error'){
                $b = $this->tran($price,$v['platform'],$v['title'],$v['cu_id']);               	
                $result[] = array_merge($list[$k],$b);   	
            }
        }
        Cache::set($key,$result);
    }
  
  
  
  
  	public function GetSixData(){
        $WapData =  ['btc','eth','bch','ltc','eos','xrp'];
        $number = Db::name('price_set')->where(['id'=>9])->value('x');
        try{
            foreach ($WapData as $k){
                $url = 'https://api.huobi.pro/market/history/kline?symbol='.$k.'usdt&period=1day&size=2';
                $ref = json_decode($this->cUrl($url))->data[1];
                $ref->close = $this->ChangePrice($ref->close);
                $set = [
                  	'time'	=>date('Y-m-d H:i:s',time()),
                    'high'  =>$ref->high,       //todo 最高价
                    'low'   =>$ref->low,        //todo 最低价
                    'open'  =>$ref->open,       //todo 开盘价
                    'close' =>$ref->close,      //todo 收盘价
                    'loss'  =>$this->ChangePrice($ref->close/$number),//todo 止损价
                ];
                $time = date('Ymd',time() - 86300);
                $map = ['name'=>$k];
                Db::name('data')->where($map)->update($set);
            }
            return 1;
        }catch (\Exception $e){
            $this->GetSixData();
        }
    }
  
  
    //todo 首页六个币种数据
    public function WapSixData(){
        $res = [];
        $huobi = [];
        $WapData =  ['btc','eth','bch','ltc','eos','xrp'];
        $number = Db::name('price_set')->where(['id'=>9])->value('x');
        foreach ($WapData as $k){
            $url = 'https://api.huobi.pro/market/detail/merged?symbol='.$k.'usdt';
            $ref = json_decode($this->cUrl($url));
            if(isset($ref->tick)){
              	if($ref->tick->close > 10){
                	$ref->tick->close = round($ref->tick->close,2);                 
                }else{
                	$ref->tick->close = round($ref->tick->close,4);  
                }
                $set = [
                    'name'  =>$k,
                    'high'  =>$ref->tick->high,       //todo 最高价
                    'low'   =>$ref->tick->low,        //todo 最低价
                    'open'  =>$ref->tick->open,       //todo 开盘价
                    'close' =>$ref->tick->close,      //todo 收盘价
                    'loss'  =>$ref->tick->close/$number,//todo 止损价
                ];
                array_push($res,$set);                    	
                $array = [
                    'name'	=>$k,
                    'price'	=>$ref->tick->close,
                    'time'	=>time(),
                ];
                array_push($huobi,$array);
            }
        }
        Db::name('huobi_data')->insertAll($huobi);
        Cache::set('huobi',$huobi);
        Cache::set($this->Key,$res);
    }
    
    //todo 每天0.8点获取平台所有币种 算出暴涨等价格
    public function AllCurrencyList(){
        $key = 'AllCurrencyList';
        $list = Db::name('currency')
            ->alias('a')
            ->join('currency b','a.pid=b.cu_id')
            ->where(['a.pid'=>['>',0],'a.type'=>1])
            ->field('a.cu_id,a.title,b.title as platform')
            ->select();
      	$re = ['b1'=>0,'b2'=>0,'b3'=>0,'s1'=>0,'s2'=>0,'s3'=>0];
        Db::name('height_remind')->where(['uid'=>['<',999999]])->update($re);
        if(!$list)return false;
        foreach ($list as $k=>$v){
            $price = 'api error';
            switch ($v['platform']){               
                case 'ZB';
                    $api = 'http://api.zb.cn/data/v1/kline?market='.$v['title'].'_usdt&size=2&type=1day';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data->data))$price = $data->data[0][4]; 
                    break;
                case 'OKEx';                   
                    $api = 'https://www.okex.com/api/spot/v3/instruments/'.strtoupper($v['title']).'-USDT/candles?granularity=86400';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data))$price = $data[1][4];;
                    break;
                case 'Huobi';
                    $api = "https://api.huobi.pro/market/history/kline?period=1day&size=2&symbol=".$v['title']."usdt";
                    $data = json_decode($this->cUrl($api));
                    if(isset($data->data[1]->close))$price =$data->data[1]->close;
                    break;
                case 'Binance';
                    $api = 'https://api.binance.com/api/v1/klines?symbol='.strtoupper($v['title']).'USDT&interval=1d&limit=2';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data[0]))$price =$data[0][4];	
                    break;
                case 'Gate.io';
                    $api = 'https://data.gateio.co/api2/1/candlestick2/'.$v['title'].'_usdt?group_sec=86400&range_hour=24';
                    $data = json_decode($this->cUrl($api));
                    if(isset($data->data[0][2]))$price =$data->data[0][2];
                    break;
                default;
                    $price = 'api error';
                    break;
            }
            if($price != 'api error'){
                $b = $this->tran($price,$v['platform'],$v['title'],$v['cu_id']);
              	$message = Db::name('message_model')->where(['id'=>5])->find();
      			$msg =  $this->GetMessage($message['content'],$message['title'],$b);
      			if(!$msg)continue;	
        		$map= ['cu_id'=>$v['cu_id']];
        		$user = Db::name('height_remind')->where($map)->column('uid');
      			if(!$user)continue;
        		$res    =  $this->SendMsg($msg,$user,5);
      			$reg_id = $this->GetPushReg($user);
      			if($reg_id)$this->PushMsg($msg['content'],$msg['title'],$reg_id);              	
                $result[] = array_merge($list[$k],$b);   	
            }
        }
        Cache::set($key,$result);
    }
    //todo 暴涨价登价格算法所有的
    private function tran($close,$platform,$title,$cu_id){
      	//var_dump($close);die;
        $x = Db::name('price_set')->column('x');
        $baoz = ($close * $x[0] - $close) * $x[2]+ $close ;     //todo 暴涨
        $zuiz = ($close * $x[0] - $close) * $x[3]+ $close; 		//todo 最高
        $ciz  =  $close * $x[4];                            	//todo 次高
        $cid  = ($close / $x[1] + $close / $x[0]) * $x[5];   	//todo 次低
        $zuid =  $close - ($close - $close / $x[1]) * $x[6];	//todo 最低
        $baod =  $close - ($close - $close / $x[1]) * $x[7]; 	//todo 暴跌
        $set = [
            'buy_1' =>      $this->ChangePrice($cid),
            'buy_2' =>      $this->ChangePrice($zuid),
            'buy_3' =>      $this->ChangePrice($baod),
            'sell_1'=>      $this->ChangePrice($ciz),
            'sell_2'=>      $this->ChangePrice($zuiz),
            'sell_3'=>      $this->ChangePrice($baoz),
            'platform'=>    $platform,
            'title'   =>    $title,
            'price'   =>    $this->ChangePrice($close),
          	'cu_id'	  =>	$cu_id,
        ];
      	
        $id = Db::name('jiage')->where(['platform'=>$platform,'title'=>$title])->value('id');   
        if(!$id){
            $res = Db::name('jiage')->insert($set);
        }else{
            $set['id'] = $id;
            $res = Db::name('jiage')->update($set);
        }
        return $set;
    }

    public function SignClean(){
        $set = [
            'one'   =>0,
            'two'   =>0,
            'three' =>0,
            'four'  =>0,
            'five'  =>0,
            'six'   =>0,
            'seven' =>0,
        ];
        Db::name('sign')->where(['uid'=>['<',999999]])->update($set);
        return;
    }


    public function huobiclear(){
        $map = ['time'=>['<',time()-86400*5]];
        Db::name('huobi_data')->where($map)->delete();
    }
}

